package com.study.springboot.conf;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * @author huyong
 * @Decription
 * @date 2025-03-21 14:40
 */
public class LoadBalanceConfig {

    @Bean
    public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment env, LoadBalancerClientFactory factory) {
        //获取负载均衡客户端名称，即提供服务名称
        String serviceName = env.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        //从所有服务中获取指定服务名称的服务实例
        //参数1 ：获取指定名称的所有实例名称
        //参数2 ：指定实例名称
        return new RandomLoadBalancer(factory.getLazyProvider(serviceName, ServiceInstanceListSupplier.class), serviceName);
    }
}
